begin tran
alter table fg_st_ctrl disable trigger all

select sum(qty) from fg_st_ctrl 
select sum(qty) from begin_qty
declare @sku nvarchar(30), @qty int,@qty_st int
declare @loca_code nvarchar(10), @bin_loca nvarchar(10), @org_in_note nvarchar(15), 
		@org_in_seq int, @ctn_no nvarchar(10), @pick_no nvarchar(15), @cfm_id int, @seq_no int, @assort_seq int, @pack_seq int
declare cu_sku cursor for select sku, qty from begin_qty order by 1
open cu_sku
fetch cu_sku into @sku, @qty
while @@fetch_status =0
begin
	declare cu_st 
	cursor for select loca_code, bin_loca, org_in_note, org_in_seq, 
					ctn_no, pick_no, cfm_id, seq_no, assort_seq, pack_seq, qty
	from fg_st_ctrl 
	where sku = @sku and loca_code = 'KO' and ctn_no = ''
	order by  org_in_note, org_in_seq 
 
	open cu_st
	fetch cu_st into @loca_code, @bin_loca, @org_in_note, @org_in_seq, 
					@ctn_no, @pick_no, @cfm_id, @seq_no, @assort_seq, @pack_seq, @qty_st
	while @@fetch_status = 0
	begin
	
		update fg_st_ctrl set qty = case when @qty >=  @qty_st then 0 else @qty_st - @qty end
		where loca_code= @loca_code and bin_loca =@bin_loca and  org_in_note = @org_in_note and 
				org_in_seq = @org_in_seq and ctn_no = @ctn_no and pick_no = @pick_no and
				cfm_id = @cfm_id and seq_no = @seq_no and assort_seq = @assort_seq and  pack_seq = @pack_seq and 
				sku = @sku
		select @qty = case when @qty <=  @qty_st then 0 else @qty - @qty_st end

		fetch cu_st into @loca_code, @bin_loca, @org_in_note, @org_in_seq, 
					@ctn_no, @pick_no, @cfm_id, @seq_no, @assort_seq, @pack_seq, @qty_st

		
	end
	
	
	if (@qty <> 0)
	begin
		set rowcount 1
		update fg_st_ctrl set qty = qty - @qty where sku = @sku and loca_code = 'KO' and ctn_no = ''
		if @@rowcount > 0 select @qty = 0
		set rowcount 0
	end
	if(@qty <> 0)
	begin
		set rowcount 1
		insert into fg_st_ctrl select @sku, 'KO', 'IN', a.note_no, a.seq_no, '', '', -@qty, getdate(), 0, 0, 0, 0, ''
		 from fg_stockin_dtl a, fg_stockin_hdr b 
		where sku = @sku and a.note_no = b.note_no order by trx_date desc
		if @@rowcount > 0 select @qty = 0
		set rowcount 0
	end

	update begin_qty set qty = @qty where sku = @sku
	close cu_st
	deallocate cu_st    
fetch cu_sku into @sku, @qty	
end
close cu_sku
deallocate cu_sku
select  b.style_no, * from fg_st_ctrl a join pos_sku b on a.sku = b.sku where qty < 0
select sum(qty) from fg_st_ctrl   
select sum(qty) from begin_qty
--select * from begin_qty order by qty desc
alter table fg_st_ctrl enable trigger all
commit tran
 